import {
  configureStore,
  ThunkAction,
  Action,
  combineReducers,
} from "@reduxjs/toolkit";
import userSlice from "./module/user/userSlice";
import homeSlice from "../pages/home/homeSlice";
import carSlice from "./module/car/carSlice";
import logger from "redux-logger";

import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // defaults to localStorage for web

const persistConfig = {
  key: "root",
  storage,
  // 白名单
  whitelist: ['car', 'user']
};

const reducers = combineReducers({
  user: userSlice.reducer,
  home: homeSlice.reducer,
  car: carSlice.reducer,
});


const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
});

export const persistor = persistStore(store);

// store.subscribe(() => {
//   const state = store.getState()
//   localStorage.setItem('car', JSON.stringify(state.car.car))
// })

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
